// Creating Cumulative Returns From Daily Returns Around Vintage Intro Dates
//Loading Daily Stock Return Data
use ../dta/stock_daily.dta, clear
drop float_cap
gen m=mofd(date)
sort code date
keep if m>600 

// Merging on Margin Data
gen stkcd=code
merge 1:1 stkcd date using ../src/daily_margin.dta, keep(match master) keepus(margin_hold float_cap)
drop stkcd
gen margin_to_cap=margin_hold/float_cap
replace margin_hold=margin_hold/1000000000

// Locals for Vintage Start Dates
local date2 "01/31/2013"
local date3 "09/16/2013"
local date4 "09/22/2014"

// Generating Monthly Raw Returns
foreach r in ret ret_dgtw ret_mkt{
	gen log_`r'=log(1+`r')
}


// Creating Cumulative Returns 
foreach v in 2 3 4{
	preserve
	keep if date>date("`date`v''", "MDY")
	gen date_lag=date-date("`date`v''", "MDY")
	tsset code date
	foreach r in ret ret_dgtw ret_mkt{
		bys code (date): gen cum_log_`r'=sum(log_`r')
		bys code (date): gen car_`r'=sum(`r')
		gen cum_`r'=exp(cum_log_`r')-1
	}
	keep if date_lag<365
	keep code date_lag ret cum_* car_* margin_hold margin_to_cap
	// Selecting Trading Days
	tsfill, full
	bys date_lag: egen max_ret=max(ret)
	keep if max_ret!=.
	bys code (date_lag):gen n=_n
	drop  ret max_ret date_lag
	// Reshaping to Store Returns and Margins at various horizons
	reshape wide cum_* car_* margin_hold margin_to_cap, i(code) j(n)
	gen rd_group=`v'
	tempfile daily_`v'
	save `daily_`v''
	restore
}

// Appending
clear
foreach x in 2 3 4{
	append using `daily_`x''
}

save ../dta/daily_returns_rd.dta, replace


